import React, { useEffect, useState } from 'react';
import { App, Button, Popconfirm, Space, Table, Tag, message } from 'antd';
import type { GetProp, TableProps } from 'antd';
import API from '@/api';
import { IPageListRow } from '@/types/article';
// import {useEffectOnActive} from 'keepalive-for-react';

type ColumnsType<T extends object> = TableProps<T>['columns'];
type TablePaginationConfig = Exclude<GetProp<TableProps, 'pagination'>, boolean>;

interface TableParams {
  pagination?: TablePaginationConfig;
  sortField?: string;
  sortOrder?: string;
  filters?: Parameters<GetProp<TableProps, 'onChange'>>[1];
}

const Home: React.FC = () => {


  // useEffectOnActive((active: any) => {
  //     console.log('useOnActive', active);
  // }, false, []);
  const columns: ColumnsType<IPageListRow> = [
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
      render: (text) => <a href='1'>{text}</a>,
    },
    {
      title: '阅读数',
      dataIndex: 'read_count',
      key: 'read_count',
      render: (text) => <span>{text}次</span>,
    },
    {
      title: '点赞数',
      dataIndex: 'like_count',
      key: 'like_count',
      render: (text) => <span>{text}次</span>,
    },
    {
      title: '评论数',
      dataIndex: 'comment_count',
      key: 'comment_count',
      render: (text) => <span>{text}条</span>,
    },
    {
      title: '发布状态',
      key: 'status',
      dataIndex: 'status',
      render: (state: number) => (
        <Tag color={ Number(state) === 1 ? 'volcano' : 'blue' }>{ Number(state) === 1 ? '待审核' : '审核通过' }</Tag>
      ),
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate',
      key: 'pubdate'
    },
    {
      title: '操作',
      key: 'action',
      width: 160,
      render: (_, record) => (
        <>
          <Button type='text' className='orange-text-btn'>编辑</Button>
          <Popconfirm
            title="提示"
            description={`确定删除${record.title}吗？`}
            okText="确定"
            cancelText="取消"
            onConfirm={ () => onDelete(record) }
            okButtonProps={{ loading: confirmLoading }}
          >
            <Button type="text" danger>删除</Button>
          </Popconfirm>
        </>
      ),
    },
  ];
  const { message } = App.useApp();
  const [confirmLoading, setConfirmLoading] = React.useState(false)
  const [loading, setLoading] = useState(false);
  const [tableData, setTableData] = useState<Array<IPageListRow>>([]);
  const [tableParams, setTableParams] = useState<TableParams>({
    pagination: {
      position: ['bottomRight'],
      total: 0,
      current: 1,
      pageSize: 2,
    },
  });
  const getList = async () => {
    try {
      setLoading(true)
      const res = await API.article.getPageList({ page: tableParams.pagination?.current, per_page: tableParams.pagination?.pageSize })
      setTableData(res.data.results)
      setTableParams({ ...tableParams, pagination: { ...tableParams.pagination, total: res.data.total_count }});
    } catch (error) {}
    finally {
      setLoading(false)
    }
  }

  const onTableChange: TableProps['onChange'] = (pagination, filters, sorter) => {
    setTableParams({ pagination, filters, ...sorter });
    if (pagination.pageSize !== tableParams.pagination?.pageSize) setTableData([]);
  };

  const onDelete = async (record: IPageListRow) => {
    try {
      setConfirmLoading(true)
      await API.article.delete(record.id)
      message.success('删除成功')
      getList()
      setConfirmLoading(false)
    } catch(_) {
      setConfirmLoading(false)
    }
  }
  useEffect(() => {
    getList()
  }, [tableParams.pagination?.current, tableParams.pagination?.pageSize])

  return (
    <div className='home-container'>
      <Table loading={loading} columns={columns} rowKey={(record) => record.id} rowClassName={(_, i) => (i % 2 === 1 ? "even" : "odd")} pagination={tableParams.pagination} dataSource={tableData} onChange={onTableChange} />
    </div>
  );
};

export default Home;

